package com.streetsmart;
/**
 * 
 * @author bhavani sudha
 *
 */
import com.streetsmart.main.SSMyApplication;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
/**
 * 
 * broadcasts location updates every 1 minute
 *
 */
public class LocationService extends Service {
	
	private static Context context;
	
	@Override
	public void onStart(Intent intent, int startId) {

		super.onStart(intent, startId);
		addLocationListener();
	}

	private void addLocationListener() {
		Thread triggerService = new Thread(new Runnable() {
			public void run() {
				try {
					Looper.prepare();// Initialise the current thread as a
										// looper.
					LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
					/*
					 * Criteria c = new Criteria();
					 * c.setAccuracy(Criteria.ACCURACY_COARSE);
					 * 
					 * final String PROVIDER = lm.getBestProvider(c, true);
					 */

					MyLocationListener mylocationlistener = new MyLocationListener();
					if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
						lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
								60000, 200f, mylocationlistener);
					} lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
							60000, 200f, mylocationlistener);
						
					// lm.requestLocationUpdates(PROVIDER, 30000, 0,
					// mylocationlistener);
					Log.d("LOC_SERVICE", "Service RUNNING!");
					Looper.loop();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
			}
		}, "LocationThread");
		triggerService.start();
	}

	

	public static void updateLocation(Location location) {
		Context appCtx = SSMyApplication.getAppContext();

		double latitude, longitude;

		latitude = location.getLatitude();
		longitude = location.getLongitude();

		Intent filterRes = new Intent();
		filterRes.setAction("android.intent.action.LOCATION");
		filterRes.putExtra("latitude", latitude);
		filterRes.putExtra("longitude", longitude);
		appCtx.sendBroadcast(filterRes);
	}

	class MyLocationListener implements LocationListener {

		public void onLocationChanged(Location location) {
			updateLocation(location);
		}

		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
		}

		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
		}
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
}
